package org.example.springoauth2.securitycommon.config.authenticate.grant.tt;

import lombok.AllArgsConstructor;
import org.example.springoauth2.securitycommon.service.SysUserService;
import org.example.springoauth2.securitycommon.util.SecurityUtil;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author hzq
 * @since 2021-09-12
 */
@AllArgsConstructor
public class TtAuthenticationProvider implements AuthenticationProvider {

    private final SysUserService sysUserService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        // TtAuthenticationToken authenticationToken = (TtAuthenticationToken) authentication;

        String ttOpenid = SecurityUtil.obtainOpenidByPrincipal(authentication.getPrincipal());

        UserDetails userDetails = sysUserService.loadUserByTtOpenid(ttOpenid);

        TtAuthenticationToken token = new TtAuthenticationToken(userDetails);

        token.setDetails(authentication.getDetails());

        return token;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.isAssignableFrom(TtAuthenticationToken.class);
    }
}
